extends CharacterBody2D

@export var min_range := 4
@export var max_range := 128
var speed:float = 30.0
const FRICTION = 500
const HIT_EFFECT = preload("uid://dyiv1y0tcwgoq")
const BAT_DIE_EFFECT = preload("uid://c2273ca8cfsrk")
const HEARTS_UI = preload("uid://b4n4qeyc6vxjf")

@onready var animation_tree: AnimationTree = $AnimationTree
@onready var sprite_2d: Sprite2D = $Sprite2D
@onready var playback :AnimationNodeStateMachinePlayback= animation_tree.get("parameters/StateMachine/playback")
@onready var ray_cast_2d: RayCast2D = $RayCast2D
@onready var hurt_box: HurtBox = $HurtBox
@onready var center: Marker2D = $Center
@onready var navigation_agent_2d: NavigationAgent2D = $Marker2D/NavigationAgent2D
@onready var marker_2d: Marker2D = $Marker2D
# @onready var hearts_ui: PackedScene = $Sprite2D2/HeartsUI
@onready var sprite_2d2: Sprite2D = $Sprite2D2

@export var stat:Stat
var player: Player

func _ready()->void:
	hurt_box.hurt.connect(do_hit.call_deferred)
	stat = stat.duplicate()
	var hearts_ui := HEARTS_UI.instantiate()
	hearts_ui.player_stat = stat
	sprite_2d2.add_child(hearts_ui)
	#如果没有血了就释放蝙蝠
	stat.no_health.connect(die)
	player = get_player()
	#navigation_agent_2d.velocity_computed.connect(_on_velocity_computed)

	

func do_hit(otherhitbox: HitBox) ->void:
	velocity = otherhitbox.knockback_direction * otherhitbox.knockback_num
	playback.start("击中状态")
	#击中后需要扣血
	stat.health -= otherhitbox.damage
	print("蝙蝠当前血量",stat.health)
	#增加击中效果
	var hit_effect = HIT_EFFECT.instantiate()
	get_tree().current_scene.add_child(hit_effect)
	hit_effect.global_position = center.global_position
	
func die() -> void:
	var batdie_effect = BAT_DIE_EFFECT.instantiate()
	get_tree().current_scene.add_child(batdie_effect)
	batdie_effect.global_position = global_position
	# 击杀后恢复玩家血量和得分
	if player:
		player.add_health(1)
		player.add_score(1)
	queue_free()

# 
func _physics_process(delta: float) -> void:
	var state = playback.get_current_node()

	match state:
		"待机": 
			pass
		
		"追逐": 
			if player is Player:
				navigation_agent_2d.target_position = player.global_position
				if navigation_agent_2d.is_navigation_finished():
					return
				#返回一个归一化的向量
				var next_point = navigation_agent_2d.get_next_path_position()
				var new_velocity = global_position.direction_to(next_point-marker_2d.position) * speed
				
				if navigation_agent_2d.avoidance_enabled:
					navigation_agent_2d.set_velocity(new_velocity)
				else:
					velocity = new_velocity
					#设置蝙蝠面向方向，根据传入的值返回-1或1
					if velocity.x != 0.0:
						sprite_2d.scale.x = sign(velocity.x)
					
			else :
				velocity = Vector2.ZERO
			move_and_slide()
		"击中状态":
			#加速度需要乘以每一帧的时间
			velocity = velocity.move_toward(Vector2.ZERO,FRICTION * delta)
			move_and_slide()

#获取玩家对象		
func get_player()->Player:
	return get_tree().get_first_node_in_group("player")

#检查玩家是否在蝙蝠可见范围内
func is_player_in_range()->bool:
	var result:=false
	if player is Player:
		var distance := global_position.distance_to(player.global_position)
		if distance>=min_range and distance <= max_range:
			result = true
	
	return result

#视线检测范围内，是否可以看到玩家
func can_see_player() -> bool:
	if not is_player_in_range(): return false
	#设置玩家位置作为视线检测目标
	ray_cast_2d.target_position = player.global_position-global_position
	#第一帧检测不到障碍物，需要强制更新一下
	ray_cast_2d.force_raycast_update()
	#视线可以达到玩家
	var has_los_to_player = not ray_cast_2d.is_colliding()
	return has_los_to_player
	
## 开启了壁障功能才会用这个安全速度
#func _on_velocity_computed(safe_velocity: Vector2):
	#velocity = safe_velocity
	#move_and_slide()
